using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseWrite.API.Applications.Commands.Questions;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters.Questions
{
    /// <summary>
    /// 修改常见问题命令处理
    /// </summary>
    public class UpdateProblemCommandHandler : IRequestHandler<UpdateProblemCommand, ApiResult<bool>>
    {
        /// <summary>
        /// 问题仓储
        /// </summary>
        private readonly IBaseRepository<ProblemManagementModel> _problemRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<UpdateProblemCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="problemRepository">问题仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public UpdateProblemCommandHandler(
            IBaseRepository<ProblemManagementModel> problemRepository,
            IMapper mapper,
            ILogger<UpdateProblemCommandHandler> logger)
        {
            _problemRepository = problemRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理修改常见问题命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> Handle(UpdateProblemCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证输入参数
                if (request.Id <= 0)
                {
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "问题ID必须大于0",
                        data = false
                    };
                }

                _logger.LogInformation("开始处理常见问题修改命令，ID：{Id}", request.Id);

                // 查找要修改的问题
                var existingProblem = await _problemRepository.GetAll()
                    .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken);

                if (existingProblem == null)
                {
                    _logger.LogWarning("未找到指定的常见问题，ID：{Id}", request.Id);
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "未找到指定的常见问题",
                        data = false
                    };
                }

                // 检查标题是否与其他问题重复（排除当前问题）
                var duplicateTitle = await _problemRepository.GetAll()
                    .Where(x => x.ProblemTitle == request.ProblemTitle && x.Id != request.Id)
                    .AnyAsync(cancellationToken);

                if (duplicateTitle)
                {
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.error,
                        message = "常见问题标题已存在！",
                        data = false
                    };
                }

                // 更新问题信息
                existingProblem.ProblemTitle = request.ProblemTitle;
                existingProblem.ProblemType = request.ProblemType;
                existingProblem.Isrecommended = request.Isrecommended;
                existingProblem.ProblemContent = request.ProblemContent;
                existingProblem.UpdatedTime = DateTime.Now;
                existingProblem.UpdatedBy = 1; // 这里应该从当前用户上下文获取

                _logger.LogDebug("常见问题信息更新完成，问题信息：{@Problem}", existingProblem);

                // 保存到数据库
                _logger.LogInformation("开始保存常见问题修改到数据库");
                var result = await _problemRepository.UpdateAsync(existingProblem);
                _logger.LogInformation("数据库保存完成，影响行数：{Result}", result);

                if (result > 0)
                {
                    _logger.LogInformation("常见问题修改成功，ID：{Id}", request.Id);
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.Ok,
                        message = "常见问题修改成功",
                        data = true
                    };
                }
                else
                {
                    _logger.LogWarning("常见问题修改失败，数据库未返回影响行数");
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "常见问题修改失败",
                        data = false
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "常见问题修改过程中发生异常，ID：{Id}", request.Id);
                return new ApiResult<bool>
                {
                    code = ResultEnumCode.fails,
                    message = $"常见问题修改异常：{ex.Message}",
                    data = false
                };
            }
        }
    }
}